package com.ruoyi.info.userController;

import com.cyl.h5.config.SecurityUtil;
import com.ruoyi.chat.domain.FhChatFriend;
import com.ruoyi.chat.service.IFhChatFriendService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.index.domain.FhIndexPostinfo;
import com.ruoyi.index.domain.FhIndexPostinfoDetail;
import com.ruoyi.index.service.IFhIndexPostinfoService;
import com.ruoyi.index.service.impl.FhIndexPostinfoDetailService;
import com.ruoyi.info.domain.*;
import com.ruoyi.info.service.*;
import com.ruoyi.info.service.impl.FhInfoEquipCategoryService;
import com.ruoyi.map.domain.FhMapFishtype;
import com.ruoyi.map.service.IFhMapFishtypeService;
import com.ruoyi.system.domain.FhUser;
import com.ruoyi.system.service.IFhUserService;
import com.ruoyi.tokenTools.UserLoginToken;
import com.ruoyi.tokenTools.UserThreadLocal;
import com.ruoyi.web.core.config.LocalUserInfoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import okhttp3.*;
import okhttp3.RequestBody;
import org.apache.commons.math3.random.RandomDataGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

;

/**
 * 用户信息Controller
 *
 * @author ruoyi
 * @date 2024-11-09
 */
@Api(tags = "用户信息")
@RestController
@RequestMapping("/app/info/user")
public class UserFhInfoUserController extends BaseController
{

    //获取token过期时间
    @Value("${token.expireTime}")
    private Long expireTime;

    @Value("${txim.appid}")
    private String appid;

    @Value("${txim.appkey}")
    private String appkey;

    @Value("${txim.username}")
    private String username;

    @Value("${txim.userSig}")
    private String userSig;

    @Autowired
    private IFhInfoUserService fhInfoUserService;

    @Autowired
    private IFhInfoUserinterestService fhInfoUserinterestService;

    @Autowired
    private IFhInfoFishpointService iFhInfoFishpointService;

    @Autowired
    private IFhInfoCatchrecordService fhInfoCatchrecordService;

    @Autowired
    private IFhInfoInterestService fhInfoInterestService;

    @Autowired
    private IFhInfoMyspaceService fhInfoMyspaceService;

    @Autowired
    private IFhInfoRankrecordService fhInfoRankrecordService;

    @Autowired
    private IFhInfoLocationService fhInfoLocationService;

    @Autowired
    private IFhUserService iFhUserService;

    @Autowired
    private IFhChatFriendService fhChatFriendService;


    @Autowired
    private IFhInfoExperienceService fhInfoExperienceService;

    @Autowired
    private IFhIndexPostinfoService fhIndexPostinfoService;

    @Autowired
    private FhInfoEquipCategoryService fhInfoEquipCategoryService;

    @Autowired
    private FhInfoEquipService fhInfoEquipService;

    @Autowired
    private FhIndexPostinfoDetailService postinfoDetailService;

    @Autowired
    private IFhMapFishtypeService fishtypeService;

    /**
     * 新增用户兴趣点，钓鱼位置，钓鱼水平
     */
    @UserLoginToken
    @ApiOperation("提交兴趣点，位置，钓鱼水平")
    @Log(title = "提交兴趣点，位置，钓鱼水平", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping
    public R<String> addInterestLocationLevel(InterestLocationLevelDto interestLocationLevelDto)
    {
        try {
            Long userId = SecurityUtil.getLocalUserInfo().getId();

            FhUser fhUser = iFhUserService.selectFhUserById(userId);

            String address = interestLocationLevelDto.getAddress();
            String fhInfoUserinterestS = interestLocationLevelDto.getFhInfoUserinterestS();
            String longitude = interestLocationLevelDto.getLongitude();
            String latitude = interestLocationLevelDto.getLatitude();
            String level = interestLocationLevelDto.getLevel();

            //插入用户定位位置
            FhInfoLocation fhInfoLocation = new FhInfoLocation();
            fhInfoLocation.setUserId(userId);
            fhInfoLocation.setLocationName(address);
            fhInfoLocation.setLongitude(longitude);
            fhInfoLocation.setLatitude(latitude);
            fhInfoLocationService.insertFhInfoLocation(fhInfoLocation);
            //插入用户钓鱼水平,性别
            String gender = iFhUserService.selectFhUserById(userId).getGender();
            FhInfoUser fhInfoUser = new FhInfoUser();
            fhInfoUser.setUserId(userId);
            fhInfoUser.setLevel(level);
            fhInfoUser.setGender(gender);
            fhInfoUser.setPhone(fhUser.getPhone());
            fhInfoUser.setCrateTime(new Date());
            fhInfoUser.setImage(fhUser.getImage());
            fhInfoUser.setAddress(fhInfoLocation.getLocationName());
            fhInfoUser.setInterests(fhInfoUserinterestS);
            fhInfoUserService.insertFhInfoUser(fhInfoUser);

            //初始化用户捕获表，排名表，我的空间表
            FhInfoCatchrecord fhInfoCatchrecord = new FhInfoCatchrecord();
            fhInfoCatchrecord.setUserId(userId);
            fhInfoCatchrecord.setCatchNum(0L);
            fhInfoCatchrecord.setCatchType(0L);
            fhInfoCatchrecord.setFishPoind(0L);
            fhInfoCatchrecordService.insertFhInfoCatchrecord(fhInfoCatchrecord);
            FhInfoRankrecord fhInfoRankrecord = new FhInfoRankrecord();
            fhInfoRankrecord.setUserId(userId);
            fhInfoRankrecord.setFriendRank(0L);
            fhInfoRankrecord.setAreaRank(0L);
            fhInfoRankrecordService.insertFhInfoRankrecord(fhInfoRankrecord);
            FhInfoMyspace fhInfoMyspace = new FhInfoMyspace();
            fhInfoMyspace.setUserId(userId);
            fhInfoMyspace.setPostNum(0L);
            fhInfoMyspace.setRecentlyView(0L);
            fhInfoMyspaceService.insertFhInfoMyspace(fhInfoMyspace);
            return R.ok("提交成功");
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取用户信息详细信息
     */
    @UserLoginToken
    @ApiOperation("获取用户信息详细信息")
    @GetMapping()
    public R<FhInfoUserVo> getInfo( )
    {
        try {
            FhInfoUserVo fhInfoUserVo = new FhInfoUserVo();

            Long userId = SecurityUtil.getLocalUserInfo().getId();
            FhInfoUser fhInfoUser1 = new FhInfoUser();
            fhInfoUser1.setUserId(userId);
            FhInfoUser fhInfoUser = fhInfoUserService.selectFhInfoUserList(fhInfoUser1).get(0);
            BeanUtils.copyProperties(fhInfoUser,fhInfoUserVo);
            //计算用户当前经验百分比
            Long nowExperience = fhInfoUser.getExperience();
            Long grade = fhInfoUser.getGrade();
            FhInfoExperience fhInfoExperience = fhInfoExperienceService.selectFhInfoExperienceById(grade + 1);
            Long experienceMax = fhInfoExperience.getExperienceMax();
            Long  schedule =  (nowExperience*100)/ (experienceMax);
            fhInfoUserVo.setExperience(schedule);
            fhInfoUserVo.setNowExperience(nowExperience);
            fhInfoUserVo.setMaxExperience(experienceMax);
            return R.ok(fhInfoUserVo);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 修改用户信息
     */
    @UserLoginToken
    @ApiOperation("修改用户信息")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<String> edit(FhInfoUser fhInfoUser)
    {
        try {
            Long userId = SecurityUtil.getLocalUserInfo().getId();
            //根据用户id查找用户信息
            FhInfoUser fhInfoUser1 = fhInfoUserService.selectFhInfoUserByUserId(userId);
            fhInfoUser.setId(fhInfoUser1.getId());
            fhInfoUser.setUserId(userId);
            fhInfoUserService.updateFhInfoUser(fhInfoUser);
            //修改用户账号表姓名
            FhUser fhUser = new FhUser();
            fhUser.setId(userId);
            fhUser.setName(fhInfoUser.getName());
            fhUser.setImage(fhInfoUser.getImage());
            iFhUserService.updateFhUser(fhUser);
            //修改im信息
            String s = registerImUser(fhUser);
            return R.ok("修改成功");
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 删除账号
     */

    @UserLoginToken
    @ApiOperation("删除账号")
    @Log(title = "删除账号", businessType = BusinessType.DELETE)
    @DeleteMapping()
    @Transactional(rollbackFor = Exception.class)
    public R<String> removeUser()
    {
        try {
            Long userId = SecurityUtil.getLocalUserInfo().getId();
            //删除用户信息
            FhInfoUser fhInfoUser = new FhInfoUser();
            fhInfoUser.setUserId(userId);

            Long id = fhInfoUserService.selectFhInfoUserList(fhInfoUser).get(0).getId();
            fhInfoUserService.deleteFhInfoUserById(id);
            //删除用户账号
            iFhUserService.deleteFhUserById(userId);
            return R.ok("删除账号成功");
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 查询渔获记录
     */
    @UserLoginToken
    @ApiOperation("查询渔获记录")
    @GetMapping("/catchRecord")
    public R<FhInfoCatchrecord> catchRecord()
    {
        try {
            FhInfoCatchrecord fhInfoCatchrecord = new FhInfoCatchrecord();
            fhInfoCatchrecord.setUserId(UserThreadLocal.getUser());
            List<FhInfoCatchrecord> list = fhInfoCatchrecordService.selectFhInfoCatchrecordList(fhInfoCatchrecord);
            return R.ok(list.get(0));
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 查询我的空间列表
     */
    @UserLoginToken
    @ApiOperation("查询我的空间")
    @GetMapping("/mySpace")
    public R<FhInfoMyspaceVo> mySpace()
    {
        try{
            FhInfoMyspaceVo fhInfoMyspaceVo = new FhInfoMyspaceVo();

            FhInfoMyspace fhInfoMyspace = new FhInfoMyspace();
            Long userId = SecurityUtil.getLocalUserInfo().getId();
            fhInfoMyspace.setUserId(userId);
            List<FhInfoMyspace> list = fhInfoMyspaceService.selectFhInfoMyspaceList(fhInfoMyspace);
            BeanUtils.copyProperties(list.get(0),fhInfoMyspaceVo);
            //根据用户id查询用户最近一次的发布记录;
            FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
            fhIndexPostinfo.setUserId(userId);
            List<FhIndexPostinfo> fhIndexPostinfoList = fhIndexPostinfoService.selectFhIndexPostinfoList(fhIndexPostinfo);
            if(fhIndexPostinfoList.isEmpty()){
                return R.ok(fhInfoMyspaceVo);
            }
            Long postId = fhIndexPostinfoList.get(0).getId();
            String postImages = fhIndexPostinfoService.selectFhIndexPostinfoById(postId).getPostImages();
            fhInfoMyspaceVo.setPostImages(postImages);

            list.get(0).setPostImages(postImages);
            fhInfoMyspaceService.updateFhInfoMyspace(list.get(0));

            return R.ok(fhInfoMyspaceVo);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 查询排名记录列表
     */
    @UserLoginToken
    @ApiOperation("查询排名记录列表")
    @GetMapping("/rankRecord")
    public R<RankDto> rankRecord()
    {
        try{
            //根据用户id获取用户地址，用户捕获数，c查询地区排名
            Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
            FhInfoUser fhInfoUser = fhInfoUserService.selectFhInfoUserByUserId(userId);
            FhInfoUser fhInfoUserByAddress = new FhInfoUser();
            fhInfoUserByAddress.setAddress(fhInfoUser.getAddress());

            FhInfoCatchrecord fhInfoCatchrecordByUserid = fhInfoCatchrecordService.selectFhInfoCatchrecordByUserId(userId);
            Long userCatchNum = fhInfoCatchrecordByUserid.getCatchNum();

            /**
             * 计算用户地区排名
             */
            ArrayList<RankCatchrecordDto> rankCatchrecordDtoArrayList = new ArrayList<>();
            //根据用户地址获取到用户信息列表
            List<FhInfoUser> fhInfoUserList = fhInfoUserService.selectFhInfoUserList(fhInfoUserByAddress);
            for (int i = 0; i < fhInfoUserList.size(); i++) {
                Long userId1 = fhInfoUserList.get(i).getUserId();
                FhInfoCatchrecord fhInfoCatchrecord = fhInfoCatchrecordService.selectFhInfoCatchrecordByUserId(userId1);
                RankCatchrecordDto rankCatchrecordDto = new RankCatchrecordDto();
                rankCatchrecordDto.setUserId(userId1);
                rankCatchrecordDto.setUserImage(fhInfoUserList.get(i).getImage());
                rankCatchrecordDto.setCatchNum(fhInfoCatchrecord.getCatchNum());
                rankCatchrecordDto.setUserName(fhInfoUserList.get(i).getName());
                rankCatchrecordDtoArrayList.add(rankCatchrecordDto);
            }
            //对获取到的用户地区捕获记录进行排序，计算出用户的地区排名
            rankCatchrecordDtoArrayList.sort(new Comparator<RankCatchrecordDto>() {
                @Override
                public int compare(RankCatchrecordDto o1, RankCatchrecordDto o2) {
                    Long catchNum = o1.getCatchNum();
                    Long catchNum1 = o2.getCatchNum();
                    return catchNum1.compareTo(catchNum);
                }
            });
            int userAreaRank = 1;
            //计算用户地区排名
            for (int i = 0; i < rankCatchrecordDtoArrayList.size(); i++) {
                if(rankCatchrecordDtoArrayList.get(i).getCatchNum() != userCatchNum){
                    userAreaRank+=1;
                }else {
                    break;
                }
            }


            /**
             * 计算用户好友排名
             */
            List<RankCatchrecordDto> rankCatchrecordDtoFriendList = new ArrayList<>();
            //根据用户id获取到用户好友列表
            FhChatFriend fhChatFriend = new FhChatFriend();
            fhChatFriend.setUserId(userId);
            List<FhChatFriend> fhChatFriends = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
            for (int i = 0; i < fhChatFriends.size(); i++) {
                Long friendId = fhChatFriends.get(i).getFriendId();
                FhInfoCatchrecord fhInfoCatchrecord = fhInfoCatchrecordService.selectFhInfoCatchrecordByUserId(friendId);
                FhInfoUser fhInfoUser1 = fhInfoUserService.selectFhInfoUserByUserId(friendId);
                RankCatchrecordDto rankCatchrecordDto = new RankCatchrecordDto(friendId,fhInfoCatchrecord.getCatchNum(),fhInfoUser1.getImage());
                rankCatchrecordDto.setUserName(fhInfoUser1.getName());
                rankCatchrecordDtoFriendList.add(rankCatchrecordDto);
            }
            rankCatchrecordDtoFriendList.add(new RankCatchrecordDto(Long.valueOf(userId),fhInfoCatchrecordByUserid.getCatchNum(),fhInfoUser.getImage()));

            //对获取到的用户地区捕获记录进行排序，计算出用户的好友排名
            rankCatchrecordDtoFriendList.sort(new Comparator<RankCatchrecordDto>() {
                @Override
                public int compare(RankCatchrecordDto o1, RankCatchrecordDto o2) {
                    Long catchNum = o1.getCatchNum();
                    Long catchNum1 = o2.getCatchNum();
                    return catchNum1.compareTo(catchNum);
                }
            });
            int userFriendRank = 1;
            //计算用户好友排名
            for (int i = 0; i < rankCatchrecordDtoFriendList.size(); i++) {
                if(rankCatchrecordDtoFriendList.get(i).getCatchNum()!=userCatchNum){
                    userFriendRank+=1;
                }else {
                    break;
                }
            }
            //更新用户排名表
            FhInfoRankrecord fhInfoRankrecord = new FhInfoRankrecord();
            fhInfoRankrecord.setUserId(userId);
            Long userAreaRank1 = (long) userAreaRank;
            fhInfoRankrecord.setAreaRank(userAreaRank1);
            Long userFriend1 = (long) userFriendRank;
            fhInfoRankrecord.setFriendRank(userFriend1);
            fhInfoRankrecord.setCrateTime(new Date());
            fhInfoRankrecordService.updateFhInfoRankrecordByUserId(fhInfoRankrecord);

            //返回数据，地区排名，地区排名列表，好友排名，好友排名列表
            RankDto rankDto = new RankDto();
            rankDto.setAreaRank(userAreaRank);
            if(rankCatchrecordDtoArrayList.size()==1){
                rankDto.setRankCatchrecordAreaList(rankCatchrecordDtoArrayList.subList(0,1));
            }else if(rankCatchrecordDtoArrayList.size()==2){
                rankDto.setRankCatchrecordAreaList(rankCatchrecordDtoArrayList.subList(0,2));
            } else if(rankCatchrecordDtoArrayList.size()>=3){
                rankDto.setRankCatchrecordAreaList(rankCatchrecordDtoArrayList.subList(0,3));
            }
            rankDto.setFriendRank(userFriendRank);
            if(rankCatchrecordDtoFriendList.size()==1){
                rankDto.setRankCatchrecordFriendList(rankCatchrecordDtoFriendList.subList(0,1));
            }else if(rankCatchrecordDtoFriendList.size()==2){
                rankDto.setRankCatchrecordFriendList(rankCatchrecordDtoFriendList.subList(0,2));
            } else if(rankCatchrecordDtoFriendList.size()>=3){
                rankDto.setRankCatchrecordFriendList(rankCatchrecordDtoFriendList.subList(0,3));
            }

            return R.ok(rankDto);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取装备分类
     */
    @UserLoginToken
    @ApiOperation("获取装备分类列表")
    @GetMapping("/getEquipCategory")
    public R<List<FhInfoEquipCategory>> getEquipCategory(){
        try {
            FhInfoEquipCategory fhInfoEquipCategory = new FhInfoEquipCategory();
            List<FhInfoEquipCategory> fhInfoEquipCategories = fhInfoEquipCategoryService.selectList(fhInfoEquipCategory);
            return R.ok(fhInfoEquipCategories);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }


    /**
     * 根据装备分类获取装备
     */
    @UserLoginToken
    @ApiOperation("根据装备分类获取装备")
    @GetMapping("/getEquip")
    public R<Page<FhInfoEquip>> getEquip(Long categoryId, Pageable page){
        try {
            FhInfoEquip fhInfoEquip = new FhInfoEquip();
            fhInfoEquip.setCategoryId(categoryId);
            List<FhInfoEquip> fhInfoEquips = fhInfoEquipService.selectList(fhInfoEquip,page);
            return R.ok(new PageImpl<>(fhInfoEquips,page,((com.github.pagehelper.Page)fhInfoEquips).getTotal()));
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取我的装备
     */
    @UserLoginToken
    @ApiOperation("获取我的装备，可根据分类id查询")
    @GetMapping("/getMyEquip")
    public R<List<FhInfoEquip>> getMyEquip(Long categoryId){
        try {
            Long userId = SecurityUtil.getLocalUserInfo().getId();
            FhInfoUser fhInfoUser = fhInfoUserService.selectFhInfoUserByUserId(userId);
            String equips = fhInfoUser.getEquips();
            if(equips==null||equips==""){
                return R.ok();
            }
            String[] equipsList = equips.split(",");
            Long[] idList = new Long[equipsList.length];
            for (int i = 0; i < equipsList.length; i++) {
                idList[i] = Long.parseLong(equipsList[i]);
            }
            //根据id数组批量查询29
            List<FhInfoEquip> fhInfoEquips = fhInfoEquipService.selectListByIdList(idList);
            if(categoryId==null){
                return R.ok(fhInfoEquips);
            }else {
                List<FhInfoEquip> returnList = fhInfoEquips.stream()
                                .filter(equip -> equip.getCategoryId() == categoryId)
                        .collect(Collectors.toList());
                return R.ok(returnList);
            }

        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 添加我的装备
     */
    @UserLoginToken
    @ApiOperation("添加我的装备")
    @GetMapping("/addMyEquip")
    @Transactional
    public R<String> addMyEquip(FhInfoEquip equip){
        try {
            //先将装备添加到装备列表
            equip.setEquipType("1");
            equip.setCreateTime(LocalDateTime.now());
            int insert = fhInfoEquipService.insert(equip);
            if(insert<=0){
                return R.fail("添加失败");
            }
            List<FhInfoEquip> fhInfoEquips = fhInfoEquipService.selectByEntity(equip);
            Long equipId = fhInfoEquips.get(0).getEquipId();
            //将装备id，添加到用户信息里面
            Long userId = SecurityUtil.getLocalUserInfo().getId();
            FhInfoUser fhInfoUser = fhInfoUserService.selectFhInfoUserByUserId(userId);
            String equips = fhInfoUser.getEquips();
            if(equips == null||equips.isEmpty()){
                equips = String.valueOf(equipId)+",";
            }else {
                equips = equips+String.valueOf(equipId) + ",";
            }
            fhInfoUser.setEquips(equips);
            fhInfoUserService.updateFhInfoUser(fhInfoUser);
            return R.ok("添加成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            System.out.println(e.getMessage());
            return R.fail(e.getMessage());
        }
    }

    /**
     * 删除我的装备
     */
    @UserLoginToken
    @ApiOperation("删除我的装备")
    @GetMapping("/deleteMyEquip")
    @Transactional
    public R<String> deleteMyEquip(Long equipId){
        try {
            //将装备id，con用户信息里面删除
            Long userId = SecurityUtil.getLocalUserInfo().getId();
            FhInfoUser fhInfoUser = fhInfoUserService.selectFhInfoUserByUserId(userId);
            String equips = fhInfoUser.getEquips();
            if(equips == null||equips.isEmpty()){
                return R.fail("用户装备未空");
            }else {
                StringBuilder sb = new StringBuilder(equips);
                int index = sb.indexOf(String.valueOf(equipId+","));
                if (index != -1) {
                    sb.deleteCharAt(index);
                }
                equips = sb.toString();
                //更新用户的装备
                fhInfoUser.setEquips(equips);
                fhInfoUserService.updateFhInfoUser(fhInfoUser);
            }
            //删除装备信息
            fhInfoEquipService.deleteByEquipId(equipId);
            return R.ok("删除成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            System.out.println(e.getMessage());
            return R.fail(e.getMessage());
        }
    }

    /**
     * 修改我的装备
     */
    @UserLoginToken
    @ApiOperation("修改我的装备")
    @PostMapping("/updateMyEquip")
    @Transactional
    public R<String> updateMyEquip(FhInfoEquip equip){
        try {
            //将装备id，con用户信息里面删除
            fhInfoEquipService.update(equip);
            return R.ok("修改成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            System.out.println(e.getMessage());
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取所有装备信息
     */
    @UserLoginToken
    @ApiOperation("获取所有装备信息")
    @GetMapping("/getAllEquipInfo")
    public R<List<AllEquipInfoVo>> getAllEquipInfo(){
        try {
            List<AllEquipInfoVo> allEquipInfoVos = new ArrayList<>();
            List<FhInfoEquipCategory> fhInfoEquipCategories = fhInfoEquipCategoryService.selectList(new FhInfoEquipCategory());
            for (FhInfoEquipCategory fhInfoEquipCategory : fhInfoEquipCategories) {
                AllEquipInfoVo allEquipInfoVo = new AllEquipInfoVo();
                allEquipInfoVo.setEquipCategory(fhInfoEquipCategory);
                FhInfoEquip fhInfoEquip = new FhInfoEquip();
                fhInfoEquip.setCategoryId(fhInfoEquipCategory.getCategoryId());
                fhInfoEquip.setEquipType("0");
                List<FhInfoEquip> fhInfoEquips = fhInfoEquipService.selectByEntity(fhInfoEquip);
                allEquipInfoVo.setEquipList(fhInfoEquips);
                allEquipInfoVos.add(allEquipInfoVo);
            }
            return R.ok(allEquipInfoVos);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取单个装备信息
     */
    @UserLoginToken
    @ApiOperation("获取单个装备信息")
    @GetMapping("/getEquipInfo")
    public R<FhInfoEquip> getEquipInfo(Long equipId){
        try {
            //将装备id，con用户信息里面删除
            FhInfoEquip fhInfoEquip = fhInfoEquipService.selectByEquipId(equipId);
            return R.ok(fhInfoEquip);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return R.fail(e.getMessage());
        }
    }

    /**
     * 积分兑换金币
     */
    @UserLoginToken
    @ApiOperation("积分兑换金币")
    @GetMapping("/pointExchangeCoin")
    public R<String> pointExchangeCoin(Long coin){
        try {
            Long userId = SecurityUtil.getLocalUserInfo().getId();
            FhInfoUser fhInfoUser = fhInfoUserService.selectFhInfoUserByUserId(userId);
            Long points = fhInfoUser.getPoints();
            Long coins = fhInfoUser.getCoins();
            if((coin*200)>points){
                return R.fail("积分不足");
            }
            points = points - coin*200;
            coins = coins + coin;
            fhInfoUser.setPoints(points);
            fhInfoUser.setCoins(coins);
            fhInfoUserService.updateFhInfoUser(fhInfoUser);
            return R.ok("兑换成功");
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 已抓渔获
     */
    @UserLoginToken
    @ApiOperation("已抓渔获")
    @GetMapping("/catchRecordList")
    public R<List<CatchRecord>> catchRecordList(Long userId){
        try {
            List<CatchRecord> catchRecordList = new ArrayList<>();
            FhInfoCatchrecord fhInfoCatchrecord = fhInfoCatchrecordService.selectFhInfoCatchrecordByUserId(userId);
            String catchNumids = fhInfoCatchrecord.getCatchNumids();
            //统计每个字符出现的次数
            HashMap<Long, Long> catchHashMap = new HashMap<>();
            String[] split = catchNumids.split(",");
            for (String s : split) {
                long fishId = Long.parseLong(s);
                //如果字符已存在，则加一
                if(catchHashMap.containsKey(fishId)){
                    catchHashMap.put(fishId,catchHashMap.get(fishId)+1L);
                }else {
                    //否则，添加到hashMap中
                    catchHashMap.put(fishId,1L);
                }
            }
            ArrayList<Long> fishIdList = new ArrayList<>();
            //通过条目集（entrySet）遍历（遍历键值对）HashMap
            for (Map.Entry<Long, Long> entry : catchHashMap.entrySet()) {
                Long fishId = entry.getKey();
                Long value = entry.getValue();
                CatchRecord catchRecord = new CatchRecord();
                catchRecord.setFishId(fishId);
                catchRecord.setNum(value);
                FhIndexPostinfoDetail fhIndexPostinfoDetail = new FhIndexPostinfoDetail();
                fhIndexPostinfoDetail.setUserId(userId);
                fhIndexPostinfoDetail.setFishId(fishId);
                List<FhIndexPostinfoDetail> fhIndexPostinfoDetails = postinfoDetailService.selectDetailList(fhIndexPostinfoDetail);
                if(!fhIndexPostinfoDetails.isEmpty()){
                    Double weight = fhIndexPostinfoDetails.get(0).getWeight();
                    catchRecord.setWeight(weight);
                }
                catchRecordList.add(catchRecord);
                fishIdList.add(fishId);
            }
            //批量查询鱼类信息,插入鱼类信息
            List<FhMapFishtype> fhMapFishtypeList = fishtypeService.selectListByFishidList(fishIdList);
            for (CatchRecord catchRecord : catchRecordList) {
                for (FhMapFishtype fhMapFishtype : fhMapFishtypeList) {
                    if(fhMapFishtype.getId().equals(catchRecord.getFishId())){
                        catchRecord.setName(fhMapFishtype.getFishType());
                        catchRecord.setImage(fhMapFishtype.getFishImage());
                        break;//找到后退出寻魂
                    }
                }
            }
            return R.ok(catchRecordList);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 附近鱼类
     */
    @UserLoginToken
    @ApiOperation("附近鱼类")
    @GetMapping("/nearbyFishType")
    public R<List<FhMapFishtype>> nearbyFishType(String lon,String lat){
        try {
            FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
            fhIndexPostinfo.setLongitude(lon);
            fhIndexPostinfo.setLatitude(lat);
            List<FhIndexPostinfo> fhIndexPostinfoList = fhIndexPostinfoService.selectFhIndexPostinfoList(fhIndexPostinfo);
            if(fhIndexPostinfoList.isEmpty()){
                List<FhMapFishtype> fhMapFishtypes = new ArrayList<>();
                return R.ok(fhMapFishtypes);
            }
            List<String> fishIdList = new ArrayList<>();
            for (FhIndexPostinfo indexPostinfo : fhIndexPostinfoList) {
                String[] split = indexPostinfo.getFishIds().split(",");
                fishIdList.addAll(Arrays.asList(split));
            }
            HashSet<String> fishIds = new HashSet<>(fishIdList);
            List<String> strings = new ArrayList<>(fishIds);
            //鱼类ids
            List<Long> idList = new ArrayList<>();
            for (String string : strings) {
                idList.add(Long.parseLong(string));
            }
            //批量查询鱼类id
            List<FhMapFishtype> fhMapFishtypes = fishtypeService.selectListByFishidList(idList);

            return R.ok(fhMapFishtypes);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }


    //向im注册用户
    public String registerImUser(FhUser user) throws IOException {
        HashMap<String, Object> body = new HashMap<>();
        body.put("UserID", String.valueOf(user.getId()));
        body.put("Nick", user.getName());
        body.put("FaceUrl", user.getImage());
        String users = imRequest(body, "v4/im_open_login_svc/account_import");
        return users;
    }

    /**
     * 基础腾讯云im请求
     */
    public String imRequest(HashMap<String,Object> body, String apiUrl) throws IOException {
//       url实例 POST https://xxxxxx/v4/im_open_login_svc/account_import?sdkappid=88888888&identifier=admin&usersig=xxx&random=99999999&contenttype=json
        String domainName = "console.tim.qq.com";
        //sdkappid 创建应用时即时通信 IM 控制台分配的 SDKAppID
        String sdkappid = appid;
        //identifier 必须为 App 管理员账号
        String identifier = username;
        //usersig App 管理员账号生成的签名
        String usersig = userSig;
        //random 请输入随机数，范围为 0 到 4294967295
        long randomLong = new RandomDataGenerator().nextLong(0, 4294967295L);
        String random = String.valueOf(randomLong);
        //contenttype 请输入 json
        String contentType = "json";
        // 构建请求 请求头
        String url = String.format("https://%s/%s?sdkappid=%s&identifier=%s&usersig=%s&random=%s&contenttype=%s",
                domainName, apiUrl, sdkappid, identifier, usersig, random, contentType);
        //将map请求体转为RequestBody
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        String jsonBody = com.alibaba.fastjson2.JSON.toJSONString(body);
        okhttp3.RequestBody requestBody = RequestBody.create(JSON, jsonBody);
        // 发送请求并处理响应
        try {
            // 创建 OkHttp 客户端
            OkHttpClient client = new OkHttpClient();
            // 构建请求
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            Headers responseHeaders = response.headers();
            for (int i = 0; i < responseHeaders.size(); i++) {
                System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
            }
            String responseBody = response.body().string();
            return responseBody;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }



}
